package net.bblbs.zhongrx;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.bblbs.zhongrx.db.FieldMapping;
import net.bblbs.zhongrx.util.FileReader;
import net.bblbs.zhongrx.util.JsonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

import static net.bblbs.zhongrx.util.JsonUtil.keyInMappingList;

/**
 * Created by Jay on 2015/8/28 0028.
 */
public class ApplicantAdditionalFragment extends Fragment implements View.OnClickListener, View.OnFocusChangeListener{

    private static final String TAG = "ZRX_ApplicantAdditionalFragment";

    FloatingActionButton addInfo = null;
    LinearLayout ll = null;

    public ApplicantAdditionalFragment() {
    }

    SectionListActivity  parent;
    private String personId;
    ArrayList<FieldMapping> mappingList = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.applicant_additional_fragment, container, false);


        parent = (SectionListActivity) getActivity();
        personId = parent.person.getId();

        ll= (LinearLayout) view.findViewById(R.id.ll_additional_info);

        addInfo = (FloatingActionButton) view.findViewById(R.id.add_info);
        addInfo.setOnClickListener(this);

        mappingList = new FileReader(parent).processFile(R.raw.fields);

        bindViews(view);
        return view;


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_info:
                AlertDialog.Builder alert = new AlertDialog.Builder(parent);
                final EditText edittext = new EditText(parent);
                alert.setTitle("添加资料");
                alert.setMessage("请输入资料字段名称");


                alert.setView(edittext);
                alert.setPositiveButton("确定", null);
                alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // what ever you want to do with No option.
                    }
                });

                final AlertDialog alertDialog = alert.create();
                alertDialog.show();
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String infoName = edittext.getText().toString().trim();

                        if (TextUtils.isEmpty(infoName)) {
                            Toast.makeText(parent, "请输入字段名称", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        SharedPreferences pref = parent.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);
                        String additional = pref.getString("dynamic_info_"+ personId,"");


                        if (JsonUtil.contains(additional, infoName)
                            || JsonUtil.keyInMappingList( mappingList, infoName)
                            ){
                            Toast.makeText(parent, "字段名称重复", Toast.LENGTH_SHORT).show();
                            return;
                        }



                        SharedPreferences.Editor editor = pref.edit();
                        editor.putString("dynamic_info_"+ personId, JsonUtil.put(additional, infoName, "")).apply();

                        LinearLayout ll_child = new LinearLayout(parent);
                        ll_child.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        ll_child.setOrientation(LinearLayout.HORIZONTAL);
                        ll_child.setPadding(0,20,0,0);

                        TextView tvKey = new TextView(parent);
                        tvKey.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
                        tvKey.setText(infoName);
                        tvKey.setTextSize(15);
                        tvKey.setSaveEnabled(false);

                        EditText etValue = new EditText(parent);
                        etValue.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));
                        etValue.setText("");
                        etValue.setSaveEnabled(false);
                        etValue.setTextSize(15);
                        etValue.setPadding(30, 0,0,0);
                        etValue.setOnFocusChangeListener(ApplicantAdditionalFragment.this);

                        ll_child.addView(tvKey);
                        ll_child.addView(etValue);
                        ll.addView(ll_child);

                        alertDialog.dismiss();
                    }
                });
        }

    }

    private void bindViews(View view) {


        for(FieldMapping map : mappingList){
            String additionalField = map.getAdditionalField();
            String basicField = map.getBasicField();

            LinearLayout ll_child = new LinearLayout(parent);
            ll_child.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            ll_child.setOrientation(LinearLayout.HORIZONTAL);
            ll_child.setPadding(0,30,0,0);

            TextView tvKey = new TextView(parent);
            tvKey.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
            tvKey.setText(additionalField);
            tvKey.setSaveEnabled(false);

            if (TextUtils.isEmpty(basicField)
                ||TextUtils.isEmpty(JsonUtil.getValueFromXin(parent.person, basicField)))
            {
                EditText etValue = new EditText(parent);
                etValue.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));

                SharedPreferences pref = parent.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);
                String additional = pref.getString("dynamic_info_"+ personId,"");
                String value = "";
                if (!TextUtils.isEmpty(additional)){
                    try{
                        JSONObject additionalJson = new JSONObject(additional);
                        value = (String) additionalJson.get(additionalField);
                    }catch (JSONException e){

                    }

                }
                etValue.setText(value);
                etValue.setSaveEnabled(false);
                etValue.setPadding(30, 0,0,0);
                etValue.setOnFocusChangeListener(this);
                ll_child.addView(tvKey);
                ll_child.addView(etValue);
                ll.addView(ll_child);
            }else{

                TextView tvValue = new TextView(parent);
                tvValue.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));
                tvValue.setText(JsonUtil.getValueFromXin(parent.person, basicField));
                tvValue.setSaveEnabled(false);
                ll_child.addView(tvKey);
                ll_child.addView(tvValue);
                ll.addView(ll_child);
            }

        }


        try {
            SharedPreferences pref = parent.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);
            String additionalData = pref.getString("dynamic_info_" + personId, "");

            if (TextUtils.isEmpty(additionalData)){
                return;
            }

            JSONObject additionalJson = new JSONObject(additionalData);

            Iterator<String> keys = additionalJson.keys();

            while( keys.hasNext() ) {



                String key = (String)keys.next();

                if (JsonUtil.keyInMappingList( mappingList, key)){
                    continue;
                }


                String value = (String) additionalJson.get(key);

                LinearLayout ll_child = new LinearLayout(parent);
                ll_child.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                ll_child.setOrientation(LinearLayout.HORIZONTAL);
                ll_child.setPadding(0,30,0,0);

                TextView tvKey = new TextView(parent);
                tvKey.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
                tvKey.setText(key);
                tvKey.setSaveEnabled(false);

                EditText etValue = new EditText(parent);
                etValue.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));
                etValue.setText(value);
                etValue.setSaveEnabled(false);
                etValue.setPadding(30, 0,0,0);
                etValue.setOnFocusChangeListener(this);

                ll_child.addView(tvKey);
                ll_child.addView(etValue);
                ll.addView(ll_child);

            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            if (v instanceof EditText) {
                LinearLayout container = (LinearLayout) v.getParent();

                TextView tv = (TextView) container.getChildAt(container.indexOfChild(v)-1);
                String key = tv.getText().toString();

                String value = ((EditText) v).getText().toString();
//                if (TextUtils.isEmpty(value.trim())){
//                    return;
//                }

                SharedPreferences pref = parent.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);
                String additionalData = pref.getString("dynamic_info_" + personId, "");

                pref.edit().putString("dynamic_info_" + personId , JsonUtil.put(additionalData, key,value)).apply();


            }
        }

    }

    @Override
    public void onPause(){
        super.onPause();
    }
}
